from databases import db_configs, HandleDb
from concurrent.futures import ThreadPoolExecutor


# 在这里添加任务函数  并且接收两个参数 task_id 和 task_name

# 测试
def task_print(task_id: str = '0', task_name: str = ''):
    _update_task_execution_count(task_id)
    print(f"{task_name}-{task_id}")


# 删除没有书记录的目录和内容
def task_clear_book_info(task_id: str = '0', task_name: str = ''):
    db = HandleDb(**db_configs.LOCALHOST_DB_FLASK_DEMO_CONFIG)
    # 更新任务数量
    _update_task_execution_count(task_id)

    result = db.sql("select book.id as book_id,category.table_name_content as table_name_content,category.table_name_directory as table_name_directory from book inner join category on category.id = book.category_id")
    if result != 'error' and result != 'ok':
        with ThreadPoolExecutor(15) as executor:
            futures = []
            # 任务数量
            for item in result:
                f = executor.submit(_task_clear_book, item)
                futures.append(f)


# 清除 不存在的书的目录 和 内容
def _task_clear_book(dict_: dict):
    book_id = dict_['book_id']
    table_name_content = dict_['table_name_content']
    table_name_directory = dict_['table_name_directory']

    db = HandleDb(**db_configs.LOCALHOST_DB_FLASK_DEMO_CONFIG)
    result = db.sql(f"select `{table_name_directory}`.id as d_id ,`{table_name_content}`.id as c_id from `{table_name_directory}` INNER JOIN  `{table_name_content}` on `{table_name_directory}`.book_id not in (select book.id from book) and `{table_name_content}`.directory_id = `{table_name_directory}`.id")
    if type(result) == list:
        # 目录sql where
        d_where_sql = ''
        # 内容sql where
        c_where_sql = ''
        for item in result:
            c_id = item['c_id']
            d_id = item['d_id']
            if d_id is not None:
                d_where_sql += f"id = {item['d_id']} or "
            if c_id is not None:
                c_where_sql += f"id = {item['c_id']} or "
        result_list = []
        if len(c_where_sql) > 4:
            c_where_sql = c_where_sql[0:-4]
            result1 = db.delete('content', c_where_sql)
            result_list.append(result1)
        if len(d_where_sql) > 4:
            d_where_sql = d_where_sql[0:-4]
            result2 = db.delete('directory', d_where_sql)
            result_list.append(result2)
        return result1, result2
    return 0,0


# 每执行一次任务 任务数量加1
def _update_task_execution_count(task_id):
    if not task_id:
        return
    try:
        db = HandleDb(**db_configs.LOCALHOST_DB_FLASK_DEMO_CONFIG)
        result = db.find('task', '*', f'task_id = {task_id}')
        task_execution_count = result[0]['task_execution_count'] or 0
        task_execution_count += 1
        # 更新执行任务数量
        db.update('task', {"task_execution_count": task_execution_count}, f'task_id = {task_id}')
    except Exception as e:
        print(e)
        print("更新任务数量错误!")
